#!/usr/bin/env bash
# init data
nginx_conf_base_dir="/etc/nginx/conf.d"
example="example"

# 读取数据
echo "Please Input domain:"
read domain
echo "Please Input web root directory:"
read root_directory

base_domain=${domain#*.}

# copy example
if [ ! -f "$nginx_conf_base_dir/$base_domain.conf" ];then
    cp $nginx_conf_base_dir/$example.conf $nginx_conf_base_dir/$base_domain.conf
fi

if [ ! -d "$nginx_conf_base_dir/$base_domain" ];then
    cp -r $nginx_conf_base_dir/$example $nginx_conf_base_dir/$base_domain
fi

if [ ! -f "$nginx_conf_base_dir/$base_domain/$example.conf" ];then
    cp $nginx_conf_base_dir/$example/$example.conf $nginx_conf_base_dir/$base_domain/$example.conf
fi

domain_length=${#domain}
base_domain_length=${#base_domain}
domain_prefix=${domain:0:($domain_length-$base_domain_length-1)}
mv $nginx_conf_base_dir/$base_domain/$example.conf $nginx_conf_base_dir/$base_domain/$domain_prefix.conf

# 替换内容
sed -i "s/base_domain/$base_domain/g" $nginx_conf_base_dir/$base_domain.conf
sed -i "s/domain/$domain/g" $nginx_conf_base_dir/$base_domain/$domain_prefix.conf
sed -i "s!root_directory!$root_directory!g" $nginx_conf_base_dir/$base_domain/$domain_prefix.conf
